package com.atguigu.bookcity.handler;


import com.atguigu.bookcity.exception.BookCityException;
import com.atguigu.bookcity.vo.CommonResult;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.UnauthenticatedException;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
public class GlobalExceptionHandler {

    @Value("${shiro.error}")
    private String error;

    // 全局异常处理
    @ExceptionHandler(Exception.class)
    public CommonResult globalError(Exception e) {
        e.printStackTrace();
        return CommonResult.error().message(e.getMessage());
    }

    // 自定义异常处理
    @ExceptionHandler(BookCityException.class)
    public CommonResult bookCityError(BookCityException e) {
        e.printStackTrace();
        return CommonResult.error().code(e.getCode()).message(e.getMsg());
    }

    // 未授权异常
    @ExceptionHandler(UnauthenticatedException.class)
    public CommonResult unauthenticatedExceptionError(UnauthenticatedException e) {
        e.printStackTrace();
        return CommonResult.error()
                .message("Subject don't have permissions");
    }

    @ExceptionHandler(UnauthorizedException.class)
    public CommonResult unauthenticatedExceptionError(UnauthorizedException e) {
        e.printStackTrace();
        return CommonResult.error()
                .message(e.getMessage());
    }

    //认证异常处理,密码错误
    @ExceptionHandler(IncorrectCredentialsException.class)
    public CommonResult incorrectCredentialsExceptionError(IncorrectCredentialsException e) {
        e.printStackTrace();
        return CommonResult.error()
                .message("密码错误,请重试");
    }

    //UnknownAccountException,认证异常处理错误
    @ExceptionHandler(UnknownAccountException.class)
    public CommonResult unknownAccountExceptionError(UnknownAccountException e) {
        e.printStackTrace();
        return CommonResult.error()
                .message("用户名错误,请重试");
    }

    //密码错误次数过多,冻结账号
    @ExceptionHandler(ExcessiveAttemptsException.class)
    public CommonResult excessiveAttemptsExceptionError(ExcessiveAttemptsException e) {
        e.printStackTrace();
        return CommonResult.error()
                .message("密码连续错误超过" + error + "次,账号冻结,30分钟后请重试");
    }


}
